package com.multitrack.chromb;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

import com.multitrack.R;

import java.io.File;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;

/**
 *
 */
public class MainActivity extends Activity {
    private GLSurfaceView glSurfaceView;
    //    private BitmapRenderer2 mRenderer;
    private BitmapRendererVE mRenderer;
    private static final String TAG = "MainActivity";
    private Button btnSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chromb);

        // 检查并请求权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
        }

        glSurfaceView = findViewById(R.id.gl_view);
        initGL(glSurfaceView);
        Button btnPreview = findViewById(R.id.btnPreview);
        Button btnRemoveBackground = findViewById(R.id.btnRemoveBackground);
        btnSave = findViewById(R.id.btnSave);

        btnPreview.setOnClickListener(v -> glSurfaceView.requestRender());

        btnRemoveBackground.setOnClickListener(v -> {
            mRenderer.setBackgroundColor(0.32f, 0.69f, 0.24f); // 设置绿幕颜色
            glSurfaceView.requestRender();
        });

        btnSave.setOnClickListener(v -> testSave());
        findViewById(R.id.btnOffScreenGreenProcessor).setOnClickListener(v -> {
            testOffScreen();
        });

        ((SeekBar) findViewById(R.id.sbarTolerance)).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mRenderer.setTolerance(progress * 1f / seekBar.getMax()); // 设置容差
                    glSurfaceView.requestRender();
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        ((SeekBar) findViewById(R.id.sbarThreshold)).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mRenderer.setThreshold(progress * 1f / seekBar.getMax()); // 设置程度
                    glSurfaceView.requestRender();
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void initGL(GLSurfaceView glSurfaceView) {

        glSurfaceView.setEGLContextClientVersion(2);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.src);
//        mRenderer = new BitmapRenderer2(this, bitmap);
        mRenderer = new BitmapRendererVE(this, bitmap);
        glSurfaceView.setRenderer(mRenderer);
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    private void testOffScreen() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.src);
        OffScreenGreenScreenProcessor offScreenGreenScreenProcessor = new OffScreenGreenScreenProcessor();
        offScreenGreenScreenProcessor.initialize(this, bitmap.getWidth(), bitmap.getHeight());
        Bitmap out = offScreenGreenScreenProcessor.processBitmap(bitmap);
        Log.e(TAG, "testOffScreen: " + out.getWidth() + "x" + out.getHeight());
        save(out);
    }

    private void testSave() {
        mRenderer.prepareSave();
        glSurfaceView.requestRender();
//            Bitmap result = mRenderer.saveFrame(glSurfaceView.getWidth(), glSurfaceView.getHeight());
        btnSave.postDelayed(new Runnable() {
            @Override
            public void run() {
                Bitmap result = mRenderer.getOut();
                Log.e(TAG, "run: " + result);
                if (null != result) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            save(result);
                        }
                    });
                }

            }
        }, 2000);

    }

    private void save(Bitmap result) {
        try {
            String fileName = "processed_" + System.currentTimeMillis() + ".png";
            File dir = new File(Environment.getExternalStorageDirectory(), android.os.Environment.DIRECTORY_PICTURES);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            java.io.File file = new java.io.File(dir, fileName);
            java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
            Log.e(TAG, "onCreate: " + file.getAbsolutePath() + " " + result.getWidth() + "x" + result.getHeight());
            result.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();

            // 更新媒体库
            android.content.Intent mediaScanIntent = new android.content.Intent(android.content.Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(android.net.Uri.fromFile(file));
            sendBroadcast(mediaScanIntent);
            Toast.makeText(this, "已保存至：" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        makeText(this, "Saved to output.png", LENGTH_SHORT).show();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (null != glSurfaceView) {
            glSurfaceView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != glSurfaceView) {
            glSurfaceView.onResume();
        }
    }

}
